package com.jhd.fuzhou.view.random;

import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.DoubleRandomService;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.QuestionBankOptionVo;
import com.jhd.fuzhou.vo.SupervisionInspectionContentVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;
public class DoubleRandomCheckActivity extends BaseActivity {

    private String doubleRandomInspectionContent;
    private List<SupervisionInspectionContentVo> supervisionInspectionContentVoList;//最终加入检查的问题
    private List<SupervisionInspectionContentVo> supervisionInspectionContentVoList2;//所有问题，在点击弹窗时，将supervisionInspectionContentVoList里的问题删除
    private Context context=this;
    @BindView(R.id.rv_double_check)RecyclerView rv_double_check;
//    @BindView(R.id.tv_add)TextView tv_add;
    private AlertDialog _alertDialog=null;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_double_random_check);
    }

    @Override
    protected void processLogic() {
        LinearLayoutManager layoutManage = new LinearLayoutManager(context);
        rv_double_check.setLayoutManager(layoutManage);
        if(supervisionInspectionVo.getDoubleRandomInspectionContentList()==null){
            supervisionInspectionContentVoList=new ArrayList<>();supervisionInspectionContentVoList2=new ArrayList<>();
            doubleRandomInspectionContent=getIntent().getStringExtra("doubleRandomInspectionContentList");
            if(!StringUtil.isNullOrEmpty(doubleRandomInspectionContent)){
                List<SupervisionInspectionContentVo> inspectionContentVos=JSON.parseArray(doubleRandomInspectionContent, SupervisionInspectionContentVo.class);
                //遍历上个页面传来的问题，与添加过的内容作对比，如何添加的没有就加入supervisionInspectionContentVoList
                for (SupervisionInspectionContentVo supervisionInspectionContentVo : inspectionContentVos) {
                    if(supervisionInspectionContentVo.getQuestionBankOptionVoList()!=null){
                        supervisionInspectionContentVo.setQuestionName(supervisionInspectionContentVo.getQuestionBankName());
                        supervisionInspectionContentVoList.add(supervisionInspectionContentVo);
                    }
                }
                DoubleCheckAdapter adapter=new DoubleCheckAdapter(supervisionInspectionContentVoList);
                rv_double_check.setAdapter(adapter);
            }
            getSuperviseInspectQuestionBankList();
        }else{
            if(supervisionInspectionVo.getDoubleRandomInspectionContentList2()!=null){
                supervisionInspectionContentVoList2= supervisionInspectionVo.getDoubleRandomInspectionContentList2();
            }else{
                supervisionInspectionContentVoList2=new ArrayList<>();
                getSuperviseInspectQuestionBankList();
            }
            supervisionInspectionContentVoList= supervisionInspectionVo.getDoubleRandomInspectionContentList();
            DoubleCheckAdapter adapter=new DoubleCheckAdapter(supervisionInspectionContentVoList);
            rv_double_check.setAdapter(adapter);
        }
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isCheck()){
                    finish();
                }else{
                    CustomToast.showText(context,"还有问题未选择!",3000,0,0).show();
                }
            }
        });
    }

    @OnClick({R.id.tv_add})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.tv_add:
                chooseQuestion();
                break;
        }
    }
    /*弹窗弹出问题选择*/
    private void chooseQuestion() {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_choose_double_random, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        _alertDialog.show();
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        RecyclerView rv_question_answer = (RecyclerView) view.findViewById(R.id.rv_question_answer);
        LinearLayoutManager layoutManage = new LinearLayoutManager(context);
        rv_question_answer.setLayoutManager(layoutManage);
        QuestionAdapter adapter=new QuestionAdapter();
        rv_question_answer.setAdapter(adapter);
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());                     //使用这种方式更改了dialog的框宽
        window.setAttributes(params);
    }
    public class QuestionAdapter extends RecyclerView.Adapter<QuestionAdapter.ViewHolder> {
        @Override
        public QuestionAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_double_random_question, parent, false);
            QuestionAdapter.ViewHolder viewHolder = new QuestionAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull QuestionAdapter.ViewHolder holder, int position) {
            holder.tv_choose.setText(supervisionInspectionContentVoList2.get(position).getQuestionName());
            holder.tv_choose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    _alertDialog.dismiss();
                    holder.tv_choose.setText(supervisionInspectionContentVoList2.get(position).getQuestionBankName());
                    SupervisionInspectionContentVo supervisionInspectionContentVo=supervisionInspectionContentVoList2.get(position);
                    supervisionInspectionContentVoList.add(supervisionInspectionContentVo);
                    supervisionInspectionContentVoList2.remove(supervisionInspectionContentVo);
                    DoubleCheckAdapter adapter=new DoubleCheckAdapter(supervisionInspectionContentVoList);
                    rv_double_check.setAdapter(adapter);
                }
            });
        }

        @Override
        public int getItemCount() {
            return supervisionInspectionContentVoList2.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_choose;
            RelativeLayout relativeLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_choose = itemView.findViewById(R.id.tv_choose);
            }
        }
    }

    private void showChoose(TextView textView,String id,SupervisionInspectionContentVo supervisionInspectionContentVo,List<QuestionBankOptionVo> questionBankOptionVoList) {
        LayoutInflater mLayoutInflater = LayoutInflater.from(this);
        View view = mLayoutInflater.inflate(R.layout.dialog_is_fit, null);
        final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context, R.style.ActionSheetDialogStyle);
        alertBuilder.setView(view);
        _alertDialog = alertBuilder.create();
        //获取当前Activity所在的窗体
        Window window = _alertDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        _alertDialog.show();
        ImageView iv_dismiss = (ImageView) view.findViewById(R.id.iv_dismiss);
        RecyclerView rv_question_answer = (RecyclerView) view.findViewById(R.id.rv_question_answer);
        LinearLayoutManager layoutManage = new LinearLayoutManager(context);
        rv_question_answer.setLayoutManager(layoutManage);
        if(questionBankOptionVoList!=null){
            QuestionOptionAdapter recyclerAdapter=new QuestionOptionAdapter(textView,id,supervisionInspectionContentVo,_alertDialog,questionBankOptionVoList);
            rv_question_answer.setAdapter(recyclerAdapter);
        }
        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _alertDialog.dismiss();
            }
        });
        WindowManager.LayoutParams params = window.getAttributes() ;
        params.width =(int) (getWindowManager().getDefaultDisplay().getWidth());                     //使用这种方式更改了dialog的框宽
        window.setAttributes(params);
    }

    /*选完题目后的显示*/
    public class DoubleCheckAdapter extends RecyclerView.Adapter<DoubleCheckAdapter.ViewHolder> {
        private List<SupervisionInspectionContentVo> supervisionInspectionContentVoList;

        public DoubleCheckAdapter(List<SupervisionInspectionContentVo> supervisionInspectionContentVoList) {
            this.supervisionInspectionContentVoList = supervisionInspectionContentVoList;
        }

        @NonNull
        @Override
        public DoubleCheckAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_double_check, parent, false);
            DoubleCheckAdapter.ViewHolder viewHolder = new DoubleCheckAdapter.ViewHolder(itemView);
            return viewHolder;
        }
        @Override
        public void onBindViewHolder(@NonNull DoubleCheckAdapter.ViewHolder holder, int position) {
            holder.tv_question.setText(StringUtil.isNullOrEmpty(supervisionInspectionContentVoList.get(position).getQuestionBankName())?supervisionInspectionContentVoList.get(position).getQuestionName():supervisionInspectionContentVoList.get(position).getQuestionBankName());
            holder.tv_check_number.setText("序号("+(position+1)+")");
            List<QuestionBankOptionVo> questionBankOptionVos = supervisionInspectionContentVoList.get(position).getQuestionBankOptionVoList();
            if(questionBankOptionVos!=null){
                if(supervisionInspectionContentVoList.get(position).getQuestionBankOptionId()!=null){//如果已经检查过
                    for (QuestionBankOptionVo questionBankOptionVo : questionBankOptionVos) {
                        if(supervisionInspectionContentVoList.get(position).getQuestionBankOptionId().equals(questionBankOptionVo.getId())){
                            holder.tv_answer.setText(questionBankOptionVo.getOptionName());
                            holder.tv_answer.setTextColor(getResources().getColor(R.color.header));
                            supervisionInspectionContentVoList.get(position).setQuestionBankId(questionBankOptionVo.getQuestionBankId());
                            supervisionInspectionContentVoList.get(position).setQuestionBankOptionId(questionBankOptionVo.getId());
                        }
                    }
                }else{//如果没有检查，那么判断有没有默认
                    for (QuestionBankOptionVo questionBankOptionVo : questionBankOptionVos) {
                        if(questionBankOptionVo.getDefaultItem().equals("1")){
                            holder.tv_answer.setText(questionBankOptionVo.getOptionName());
                            holder.tv_answer.setTextColor(getResources().getColor(R.color.header));
                            supervisionInspectionContentVoList.get(position).setQuestionBankId(questionBankOptionVo.getQuestionBankId());
                            supervisionInspectionContentVoList.get(position).setQuestionBankOptionId(questionBankOptionVo.getId());
                        }
                    }
                }
            }
            holder.linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showChoose(holder.tv_answer,supervisionInspectionContentVoList.get(position).getEnforceBasisId(),supervisionInspectionContentVoList.get(position),supervisionInspectionContentVoList.get(position).getQuestionBankOptionVoList());
                }
            });
            holder.tv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    supervisionInspectionContentVoList.get(position).setQuestionBankId(null);
                    supervisionInspectionContentVoList.get(position).setQuestionBankOptionId(null);
                    supervisionInspectionContentVoList2.add(supervisionInspectionContentVoList.get(position));
                    supervisionInspectionContentVoList.remove(position);
                    DoubleCheckAdapter adapter=new DoubleCheckAdapter(supervisionInspectionContentVoList);
                    rv_double_check.setAdapter(adapter);
                }
            });
        }

        @Override
        public int getItemCount() {
            return supervisionInspectionContentVoList.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_question,tv_answer,tv_check_number,tv_delete;
            LinearLayout linearLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_question = itemView.findViewById(R.id.tv_question);
                this.tv_answer = itemView.findViewById(R.id.tv_answer);
                this.tv_delete = itemView.findViewById(R.id.tv_delete);
                this.tv_check_number = itemView.findViewById(R.id.tv_check_number);
                this.linearLayout = itemView.findViewById(R.id.linearLayout);
            }
        }
    }



    public class QuestionOptionAdapter extends RecyclerView.Adapter<QuestionOptionAdapter.ViewHolder> {
        private List<QuestionBankOptionVo> questionBankOptionVoList;
        private SupervisionInspectionContentVo supervisionInspectionContentVo;
        private TextView textView;
        private String id;
        private AlertDialog _alertDialog;
        private int checkPosition=-1;
        public QuestionOptionAdapter(TextView textView,String id,SupervisionInspectionContentVo supervisionInspectionContentVo, AlertDialog _alertDialog, List<QuestionBankOptionVo> questionBankOptionVoList) {
            this.questionBankOptionVoList = questionBankOptionVoList;
            this._alertDialog = _alertDialog;
            this.textView = textView;
            this.id = id;
            this.supervisionInspectionContentVo = supervisionInspectionContentVo;
        }
        @Override
        public QuestionOptionAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_choose, parent, false);
            QuestionOptionAdapter.ViewHolder viewHolder = new QuestionOptionAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull QuestionOptionAdapter.ViewHolder holder, int position) {
            holder.tv_choose.setText(questionBankOptionVoList.get(position).getOptionName());
            if(questionBankOptionVoList.get(position).getOptionName().equals(textView.getText().toString())){
                holder.image.setVisibility(View.VISIBLE);
            }else{
                if(questionBankOptionVoList.get(position).getDefaultItem().equals("1")&&textView.getText().toString().equals("请选择")){
                    holder.image.setVisibility(View.VISIBLE);
                }else{
                    holder.image.setVisibility(View.GONE);
                }
            }

            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    textView.setText(questionBankOptionVoList.get(position).getOptionName());
                    textView.setTextColor(getResources().getColor(R.color.header));
                    supervisionInspectionContentVo.setQuestionBankId(questionBankOptionVoList.get(position).getQuestionBankId());
                    supervisionInspectionContentVo.setQuestionBankOptionId(questionBankOptionVoList.get(position).getId());
                    _alertDialog.dismiss();
                    supervisionInspectionVo.setDoubleRandomInspectionContentList(supervisionInspectionContentVoList);
                    supervisionInspectionVo.setDoubleRandomInspectionContentList2(supervisionInspectionContentVoList2);
                    if(questionBankOptionVoList.get(position).getOptionName().equals("否")||questionBankOptionVoList.get(position).getOptionName().equals("不合格")){
                        if(id!=null){
                            getEnforceBasisById(id);
                        }else{
                            startActivity(new Intent(context, DoubleCheckContentActivity.class));
                        }
                    }
                }
            });

            if(position==checkPosition){
                holder.image.setVisibility(View.VISIBLE);
            }else{
                if(checkPosition!=-1){
                    holder.image.setVisibility(View.GONE);
                }
            }
        }

        @Override
        public int getItemCount() {
            return questionBankOptionVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_choose;ImageView image;
            RelativeLayout relativeLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                this.tv_choose = itemView.findViewById(R.id.tv_choose);
                this.image = itemView.findViewById(R.id.image);
                this.relativeLayout = itemView.findViewById(R.id.relativeLayout);
            }
        }
    }

    private void getSuperviseInspectQuestionBankList(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application,"http://192.168.1.94:9004/");//URL的头
        DoubleRandomService vs = retrofit.create(DoubleRandomService.class);
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("questionType","双随机抽检内容");
        params.put("specialityCategory", supervisionInspectionVo.getSpecialityCategory());
        params.put("status", supervisionInspectionVo.getBusinessStatus());
        params.put("provincialStandard",("0".equals(supervisionInspectionVo.getTaskType()))?"0":"1");
        params.put("nationalStandard",("0".equals(supervisionInspectionVo.getTaskType()))?"1":"0");
        Call<JsonForResult> jsonForResultCall = vs.getSuperviseInspectQuestionBankSpotCheckList(application.getAccessToken(), params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        //请求授权信息
                        if(jsonForResult.getData()!=null){
                            List<SupervisionInspectionContentVo> supervisionInspectionContentVos = JSON.parseArray(jsonForResult.getData().toString(), SupervisionInspectionContentVo.class);
                            if(supervisionInspectionContentVos!=null){
                                for (SupervisionInspectionContentVo supervisionInspectionContentVo : supervisionInspectionContentVos) {
                                    if(supervisionInspectionContentVo.getQuestionBankOptionVoList()!=null){
                                        supervisionInspectionContentVoList2.add(supervisionInspectionContentVo);
                                    }
                                }
                                supervisionInspectionVo.setDoubleRandomInspectionContentList2(supervisionInspectionContentVoList2);
                            }
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取检测项目失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    /*获取详情失败*/
    private void getEnforceBasisById(String id){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        SupervisionService vs = retrofit.create(SupervisionService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("id",(id==null)?"":id);
        Call<JsonForResult> jsonForResultCall = vs.getEnforceBasisById(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){//如果有数据，将数据带过去显示
                            Intent intent=new Intent(context, DoubleStandardWordActivity.class);
                            Gson gson = new Gson();
                            intent.putExtra("enforceBasis",gson.toJson (jsonForResult.getData()));
                            context.startActivity(intent);
                        }else{//如果没数据，就到页面全盘选择
                            Intent intent=new Intent(context,DoubleCheckContentActivity.class);
                            context.startActivity(intent);
                        }
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络错误!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 按下键盘上返回按钮
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(isCheck()){
                finish();
            }else{
                CustomToast.showText(context,"还有问题未选择!",3000,0,0).show();
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
    public boolean isCheck(){
        if(supervisionInspectionContentVoList!=null){
            for (SupervisionInspectionContentVo supervisionInspectionContentVo : supervisionInspectionContentVoList) {
                if(supervisionInspectionContentVo.getQuestionBankOptionId()==null){
                    return false;
                }
            }
        }
        return true;
    }
}